// var serviceUrl = 'http://test.xiaozhubiji.com/bljjs/';
var serviceUrl = 'http://www.bolojun.net/bljjs/';

var shareTitle = '菠萝君健身';
var shareDesc = '权威的健身方案解决商~';
var sharePage = '/pages/index/index';
/**
 * 调用wxwx.request请求api
 *      serviceName：api地址
 *      params：参数
 *      cb：成功回调
 *      loadingTip: loading显示的提示内容
 *      errcb：错误回调
 */
function sendRequest(methodno, params, callback, loadingTip, errcallback) {
  var user = wx.getStorageSync('userInfo') || {};
  params = params || {};
  params.appid = user.appid || '';
  params.openid = wx.getStorageSync('openid');
  params.userid = user.userid || '';
  params.usertype = user.userType || '';
  params.verify = user.verify||'';
  //TODO 加入用户登录参数
  wxShowLoading(loadingTip);

  wx.request({
    url: serviceUrl + 'weChat?methodno=' + methodno,
    data: params,
    method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {       // 设置请求的 header
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      wxHideLoading() // 关闭加载层
      const isLoginCompelete = wx.getStorageSync("isLoginCompelete");
      if (res && res.statusCode == 200 && res.errMsg == 'request:ok') {
        if (res.data && res.data.errorCode == 0) {
          var businessData = res.data.data
          // 0:正常 1:失败
          callback.call(this, businessData)
        } else if (res.data && res.data.errorCode == 1003 && isLoginCompelete) {
          wxModalAlert({
            title: '提示',
            content: '还没有登录，请先登录！'
          }, function () {
            wx.reLaunch({
              url: '/pages/index/index',
            });
          });
        } else {
          // wxModalSimpleAlert(res.data.errorCode + ':' + res.data.errorMsg)
        }
      } else {
        // 判断是否为登录失败
        if (errcallback) {
          typeof errcallback == 'function' && errcallback(res)
        } else {
          wxModalSimpleAlert(res.statusCode + ':' + res.errMsg)
        }
      }
    },
    fail: function (err) {
      // fail
      wxHideLoading()
      if (errcallback) {
        typeof errcallback == 'function' && errcallback(err)
      } else {
        wxModalSimpleAlert('与服务器通信异常')
      }
    },
    complete: function (res) {
      // complete
    }
  });
}

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function formatDate(date, fmt) { //author: meizz 
  var o = {
    "M+": date.getMonth() + 1, //月份 
    "d+": date.getDate(), //日 
    "h+": date.getHours(), //小时 
    "m+": date.getMinutes(), //分 
    "s+": date.getSeconds(), //秒 
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
    "S": date.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

function formatTimeForOrder(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('') + [hour, minute, second].map(formatNumber).join('')
}

function random(min, max) {
  var range = max - min
  var num = Math.random() * range + min
  return parseInt(num, 10)
}

function getNowFormatDate() {
  var date = new Date();
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

/**
 * 显示loading
 */
function wxShowLoading(title, cb) {
  if (!title) {
    title = '加载中'
  }
  wx.showToast({
    title: title,
    icon: 'loading',
    duration: 15000,
    success: function (res) {
      if (cb) {//回调
        typeof cb == 'function' && cb(res)
      }
      // wxHideLoading()
    },
    fail: function () {
      // wxHideLoading()
    },
    complete: function () {

    }
  })
}

/**
 * 隐藏loading
 */
function wxHideLoading() {
  wx.hideToast()
}

/**
 * toast --- alert
 */
function wxToastAlert(title, cb) {
  if (!title) {
    title = '警告'
  }
  wx.showToast({
    title: title,
    icon: 'success',
    duration: 1500,
    success: function (res) {
      if (cb) {//回调
        typeof cb == 'function' && cb(res)
      }
    }
  })
}

/**
 * 模态alert框
 */
function wxModalAlert(options, cb, cancel_cb) {
  wx.showModal({
    title: options.title ? options.title : '提示',
    content: options.content ? options.content : '提示内容',
    showCancel: options.showCancel ? options.showCancel : false,
    cancelText: options.cancelText ? options.cancelText : '取消',
    success: function (res) {
      if (res.confirm == 1) {
        if (cb) {
          typeof cb == 'function' && cb(res)
        }
      } else if (res.confirm == 0) {
        if (cancel_cb) {
          typeof cancel_cb == 'function' && cancel_cb(res)
        }
      }
    }
  })
}
/**
 * 简化
 */
function wxModalSimpleAlert(content) {
  wxModalAlert({
    title: '提示',
    content: content
  })
}

/**
 * 微信支付
 *      payoptions：支付用参数
 *      cb：成功回调
 *      errcb：失败回调
 */
function requestWxPayment(payOptions, cb, errcb) {
  wx.requestPayment({
    timeStamp: payOptions.timeStamp,
    nonceStr: payOptions.nonceStr,
    package: payOptions.package,
    signType: payOptions.signType,
    paySign: payOptions.paySign,
    success: function (res) {
      // success
      if (cb) {
        typeof cb == 'function' && cb(res)
      }
    },
    fail: function (res) {
      // fail
      if (errcb) {
        typeof errcb == 'function' && errcb(res)
      }
    },
    complete: function () {
      // complete
    }
  })
}

/**
 * 获取当前定位
 *      cb:回调函数
 */
function getLocation(cb) {
  wxShowLoading('正在定位')
  wx.getLocation({
    type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
    success: function (res) {
      // success
      if (cb) {
        typeof cb == 'function' && cb(res)
      }
    },
    fail: function () {
      // fail
      //使用默认位置
      if (cb) {
        typeof cb == 'function' && cb({
          latitude: 31.7244,
          longitude: 119.963
        })
      }
      wxToastAlert('定位失败')
    },
    complete: function () {
      // complete
      wxHideLoading()
    }
  })
}

/**
 * 打开地图
 */
function openLocation(location, cb) {
  wx.openLocation({
    latitude: location.latitude, // 纬度，范围为-90~90，负数表示南纬
    longitude: location.longitude, // 经度，范围为-180~180，负数表示西经
    scale: 28, // 缩放比例
    // name: 'name', // 位置名
    // address: 'address', // 地址的详细说明
    success: function (res) {
      // success
      if (cb) {
        typeof cb == 'function' && cb(res)
      }
    },
    fail: function () {
      // fail
      wxToastAlert('打开地图失败')
    },
    complete: function () {
      // complete
    }
  })
}

/**
 * 10以内的数字，前面补零
 */
function fmtZeroFill(num) {
  if (num < 10) {
    return "0" + num;
  } else {
    return num;
  }
}
/**
 * 校验网络状态
 */
function checkNetwork(cb) {
  getNetworkType(function (res) {
    if ('none' == res.networkType) {
      wxModalSimpleAlert('当前无网络，请检查您的手机网络')
    }
    //自定义相关函数
    if (cb) {
      typeof cb == 'function' && cb(res)
    }
  })
}

//////////////获取系统信息////////////////
/**
 * 获取系统信息
 */
function getSystemInfo(cb) {
  wx.getSystemInfo({
    success: function (res) {
      // success
      // model	手机型号
      // pixelRatio	设备像素比
      // windowWidth	窗口宽度
      // windowHeight	窗口高度
      // language	微信设置的语言
      // version	微信版本号
      // system	操作系统版本
      // platform	客户端平台
      if (cb) {
        typeof cb == 'function' && cb(res)
      }
    }
  })
}
/**
 * 获取网络类型
 */
function getNetworkType(cb) {
  wx.getNetworkType({
    success: function (res) {
      // success
      // 返回网络类型, 有效值：
      // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
      if (cb) {
        typeof cb == 'function' && cb(res)
      }
    }
  })
}
/**
 * 监听网络状态
 */
function listenNetworkStatusChange() {
  //获取当前网络状态
  checkNetwork()

  //基础库版本 1.1.0 开始支持，低版本需做兼容处理
  if (wx.onNetworkStatusChange) {
    //监听网络状态
    wx.onNetworkStatusChange(function (res) {
      if (!res.isConnected) {
        wxModalSimpleAlert('当前无网络，请检查您的手机网络')
      }
    })
  }
}

/**
 * 产生伪设备编号
 */
function generateUUID() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid;
}

/**
 * 上传用户图片
 */
function uploadImage(filePath, name, success, fail) {
  wx.uploadFile({
    url: serviceUrl + 'fileUpload?dir=image',
    filePath: filePath,
    name: name,
    header: {
      'content-type': 'multipart/form-data'
    }, // 设置请求的 header
    formData: {}, // HTTP 请求中其他额外的 form data
    success: function (res) {
      // 
      if (res.statusCode == 200 && !res.data.result_code) {
        var obj = JSON.parse(res.data);
        var headImg = obj.url.substring(obj.url.lastIndexOf('=') + 1, obj.url.length);
        obj.headImg = headImg;
        typeof success == "function" && success(obj);
      } else {
        typeof fail == "function" && fail(res);
      }
    },
    fail: function (res) {

      typeof fail == "function" && fail(res);
    }
  });
}

var questionArr = ['/pages/choose/version', "pages/personal/sex", ""];
function nextQuestion(locat) {
  var url = questionArr[locat];
  if (url == undefined) {
    var questionInfo = wx.getStorageSync('questionInfo');
    sendRequest('WxAllQuestionOver', { array: JSON.stringify(questionInfo) }, function (resp) {
      if (resp && resp.code == 0) {
        wx.redirectTo({
          url: '/pages/index/index'
        });
      } else {

      }
    }, '跳转中...', function () {

    });
  } else {
    wx.setStorageSync('nowQuestion', url);
    wx.redirectTo({
      url: url.pages
    });
  }

}

function prevQuestion(location) {
  var prevUrl = '/pages/index/index';
  for (var i = 0; i < questionArr.length; i++) {
    if (questionArr[i].location == location) {
      prevUrl = questionArr[i - 1].pages;
    }
  }
  wx.redirectTo({
    url: prevUrl
  });
}

function setLocation(arr) {
  if (arr.length > 0) questionArr = arr;
}
function getShareMsg() {
  return {
    title: shareTitle,
    desc: shareDesc,
    path: sharePage
  }
}
// auther by vijay
// 获取题目函数
// 题目类型(收费/免费)
let questionType = 0;
function getQuestion(pageNum = 0, callback,qtype) {
  
  questionType = qtype != null ? qtype : questionType;
  
  const defaultUser = { deviceid: 1, type: questionType, pos: pageNum };
  sendRequest("WXGetQuestionList", defaultUser, callback);
}
// 提交答案
function commitAnswer(answer, callback) {
  sendRequest("WXAnswerQuestion", answer, callback);

}
module.exports = {
  serviceUrl: serviceUrl,
  formatTime: formatTime,
  formatDate: formatDate,
  formatTimeForOrder: formatTimeForOrder,
  wxShowLoading: wxShowLoading,
  wxHideLoading: wxHideLoading,
  wxToastAlert: wxToastAlert,
  wxModalAlert: wxModalAlert,
  wxModalSimpleAlert: wxModalSimpleAlert,
  sendRequest: sendRequest,
  requestWxPayment: requestWxPayment,
  getLocation: getLocation,
  openLocation: openLocation,
  fmtZeroFill: fmtZeroFill,
  checkNetwork: checkNetwork,
  getSystemInfo: getSystemInfo,
  getNetworkType: getNetworkType,
  listenNetworkStatusChange: listenNetworkStatusChange,
  uploadImage: uploadImage,
  getNowFormatDate: getNowFormatDate,
  nextQuestion: nextQuestion,
  setLocation: setLocation,
  shareTitle: shareTitle,
  shareDesc: shareDesc,
  sharePage: sharePage,
  getShareMsg: getShareMsg,
  getQuestion, commitAnswer
}


